package com.wrial.test;
/*
 * @Author  Wrial
 * @Date Created in 10:31 2020/8/11
 * @Description
 */

public class HeapSort {

    public int myHeapSort(int[] arr, int k) {

        //1.建堆
        for (int i = (arr.length - 1) / 2; i >= 0; i--) {
            adjust(arr, arr.length, i);
        }

        //2.取出并调整
        for (int i = arr.length - 1; i >= 0 && k > 1; i--) {
            int temp = arr[0];
            arr[0] = arr[i];
            arr[i] = temp;
            k--;
            adjust(arr, i, 0);
        }
        return arr[0];

    }

    private void adjust(int[] arr, int length, int i) {
        int index = 2 * i + 1;
        int temp = arr[i];
        int k = i;
        while (index < length) {
            if (index + 1 < length) {
                index = arr[index] > arr[index + 1] ? index : index + 1;
            }
            if (arr[index] > temp) {
                arr[k] = arr[index];
                k = index;
                index = 2 * k + 1;
            } else {
                break;
            }

        }
        arr[k] = temp;
    }

    public static void main(String[] args) {
        int[] arr = new int[]{-1, 8, 9, 1, 0, 3};
        System.out.println(new HeapSort().myHeapSort(arr, 0));

    }

}
